#include <stdio.h>
#include <stdlib.h>
#include "Structs.h"
#include "Pong3D.h"
#include <GL/glut.h>
#include <math.h>
#include <Windows.h>


GLuint sObject = 0;
int texLoaded = 0;
GLuint ballTextures[5] = {0,0,0,0,0};

/*
Function Name: loadBallTextures
Description: helper method to load up all textures related to the balls  
Inputs:		null
returns:	null
*/
void loadBallTextures(){
	ballTextures[0] = raw_texture_load("balls\\0.tga",256,256);
	ballTextures[1] = raw_texture_load("balls\\1.tga",256,256);
	ballTextures[2] = raw_texture_load("balls\\2.tga",256,256);
	ballTextures[3] = raw_texture_load("balls\\3.tga",256,256);
	
	raw_texture_load("balls\\0.tga",256,256);

	printf("Loaded: %i, %i, %i, %i", ballTextures[0],ballTextures[1],ballTextures[2],ballTextures[3]);
}


void drawPickObjects(){
	GLfloat initPositions[4][3] = { //The four positions of the selectable balls
		{-2,2,0} , {2,2,0},
		{-2,-2,0}, {2,-2,0}
	};
	int i;
	
	GLUquadricObj *sphere = gluNewQuadric();


	//First load ball textures
	if (!texLoaded){
		loadBallTextures();
		texLoaded = 1;
	}

	//glColor3f(1,1,1);
	glInitNames();
	glPushName(0);
	glMatrixMode(GL_MODELVIEW);
	for(i=0;i<4;i++)
	{
		glPushMatrix();
		glLoadName(i);
		glPassThrough((GLfloat)i);
		glTranslatef(initPositions[i][0],initPositions[i][1],initPositions[i][2]);
		glRotatef(270,1,0,0);
		drawBall(sphere, 1, ballTextures[i]);
		glPopMatrix();
	}
}

GLuint pickObject(int x, int y)
{
	GLint hits, viewport[4];
	GLuint pickBuff[64];
	glSelectBuffer(64, pickBuff);
	glGetIntegerv(GL_VIEWPORT, viewport);
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();

	glRenderMode(GL_SELECT);
	glLoadIdentity();
	gluPickMatrix(x,viewport[3] -y, 2, 2, viewport);
	setPerspective();

	drawPickObjects();

	hits = glRenderMode(GL_RENDER);
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);

	if(hits){
		sObject = pickBuff[3];
		printf("Hit at %i , %i  hit: %i  object: %i    Texture: %i\n",x,y, hits, sObject, ballTextures[sObject]);
		return ballTextures[sObject];
	}
	printf("Picked at %i , %i  hit: %i  object: %i \n",x,y, hits, sObject);

	return -1;
}

